package com.mbti.youmore.common;

import com.mbti.youmore.entity.resp.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;

/**
 * @author Guqier
 * @version 1.0
 * @date 2024/1/23 下午 4:39
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {



    @ExceptionHandler(Exception.class)
    public ResponseData doException(Exception e) {
        log.error("系统异常：{}", getTraceToString(e));
        return ResponseData.fail(999, "系统异常");
    }

    /**
     * 数据校验异常响应结果封装方法
     * @param errorList 错误列表
     * @return 响应结果
     */
    private ResponseData extractException(List<ObjectError> errorList) {
        StringBuilder errorMsg = new StringBuilder();
        for (ObjectError objectError : errorList) {
            errorMsg.append(objectError.getDefaultMessage()).append(";");
        }
        // 移出最后的分隔符
        errorMsg.delete(errorMsg.length() - 1, errorMsg.length());
        return ResponseData.fail(101, errorMsg.toString());
    }

    /**
     * 获取异常跟踪栈信息
     * @param throwable 异常对象
     * @return 异常跟踪栈信息
     */
    public static String getTraceToString(Throwable throwable){
        StringWriter stringWriter=new StringWriter();
        PrintWriter writer=new PrintWriter(stringWriter);
        throwable.printStackTrace(writer);
        StringBuffer buffer=stringWriter.getBuffer();
        return buffer.toString();
    }


}
